public class ctlr_RenewSectionOnCompanyClass
{
    //For Variables...
    public List<Tenancy_Contract__c> tenancyContractList {get;set;}//= new List<Tenancy_Contract__c>();
    public string tenancyIdforRenewalProperty {get;set;}
    public Account accountObject{get;set;}
    public Map<ID,ID> locationTennacyContractMap = new Map<ID,ID>();
    public Boolean refreshPage {get; set;}
    //For Constructor...
    public ctlr_RenewSectionOnCompanyClass(ApexPages.StandardController controller) 
    {
        try
        {
            //Set the Refresh the page 
            refreshPage = false;
            accountObject = new Account();
            accountObject = [Select Id,Name, Number_Of_Tenancy_Contract_Renwal__c,Number_Of_Approved_Suspension_Record__c,Login_User_Id__c,LicenseNumber__c,Renewal_Process_End_Date__c,Renewal_Process_Start_Date__c,License_Application_Type__c ,License_Application_Step__c,Login_User_Profile__c, License_Expiry_Date__c, License_Validity_State__c from Account where Id =: ApexPages.CurrentPage().getParameters().get('id') ];
            //For Tenancy Contract Searching....    
            tenancyContractList = new List<Tenancy_Contract__c>();
            tenancyContractList = [Select Tenancy_Contract_Expiry_Date__c,Tenancy_Contract_Renewal_Steps__c,Renewal_Start_Date__c,Record_Type_Name__c,Account_Tenancy_Expriy_Difference__c, Name, Location__c, Contract_Status__c, Id From Tenancy_Contract__c where ((Tenancy_Contract_Cancellation_Date__c =: null) AND (Tenant__c =: ApexPages.CurrentPage().getParameters().get('id'))) LIMIT 1000];
            
            for(Tenancy_Contract__c tenancyObject :tenancyContractList )
            {
                locationTennacyContractMap.put(tenancyObject.Id,tenancyObject.Location__c);
            }
        
        }
        catch(Exception ex)
        {
            System.debug(ex.getMessage());
        }
        
    }
    
    //For Renew Tenancy Contract....
    public PageReference renewTenancyContractMethod()
    {
        try
        {
            Tenancy_Contract__c tenancyObject = new Tenancy_Contract__c();
            
            //System.debug('The Renew Tenancy Contract Id=>'+ tenancyIdforRenewalProperty);
            
            //System.debug('In Renew Class => The Account Object 3 Id=> '+ accountObject.Id + ' && The Current Record Id => '+ ApexPages.CurrentPage().getParameters().get('id') + ' && The Application Step => '+accountObject.License_Application_Step__c);
            
            if(accountObject.Login_User_Profile__c == 'SmartPaper BPM: 08 License - Front Office Payment User' || accountObject.Login_User_Profile__c == 'SmartPaper BPM: 01 Front Office User' || accountObject.Login_User_Profile__c == 'System Administrator')   
            {
                if(accountObject.License_Application_Step__c == 'Archived')
                {
                    
                    //Now Checking the All the Locations Related to the account...
                    List<Location__c> locationObjectList = new list<Location__c>([select Id,Current_Tenancy_Contract__c,name from Location__c where Current_Tenancy_Contract__c =: tenancyIdforRenewalProperty]);
                    
                    //System.debug('The Total Number Of Locations are => '+ locationObjectList.size() + ' && the Total Number of Tenancy Contracts are => ' +locationTennacyContractMap.size());
                    
                    //System.debug('In renew Class => The Tenancy Contract Id => ' + tenancyIdforRenewalProperty);
                    
                    //If the size is not equal to the tenancyObject then it is error...
                    if(locationObjectList.size() == 1)
                    {
                        
                        if(accountObject.Number_Of_Approved_Suspension_Record__c == 0)
                        {
                            Boolean isContinueRenewal = true;
                        
                            //Now Check the tenancy Contract Expired Comparison....
                            for(Tenancy_Contract__c temptenancyObject :tenancyContractList )
                            {
                                //Only search the Selected Tenancy Contract Id...
                                if(temptenancyObject.Id == tenancyIdforRenewalProperty)
                                {
                                    //Setting the Object for the Tenancy Contract...
                                    tenancyObject = temptenancyObject;
                                    //System.debug('The Account Expiry Date => '+ accountObject.License_Expiry_Date__c + ' && The Today => '+ System.today() + ' && The Account Tenancy Expiry Difference => '+ temptenancyObject.Account_Tenancy_Expriy_Difference__c + ' && The Tenancy COntract Expiry Date  => '+ temptenancyObject.Tenancy_Contract_Expiry_Date__c);
                                    if(((temptenancyObject.Account_Tenancy_Expriy_Difference__c) < integer.valueof(30)))
                                    {
                                        ApexPages.Message msg = new ApexPages.Message(ApexPages.Severity.INFO, 'Please perform the License Renewal First');
                                        ApexPages.addMessage(msg);
                                        
                                        isContinueRenewal = false;
                                        
                                        break;
                                        
                                    }
                                }
                            }
                            
                            if(isContinueRenewal)
                            {
                                //Updating the Tenancy Contract...
                                RecordType recordType = [Select SobjectType, Name, IsActive, Id From RecordType where Name = 'Under Renewal' and IsActive = true and SobjectType = 'Tenancy_Contract__c'];
                                
                                tenancyObject.RecordTypeId = recordType.id;
                                tenancyObject.Renewal_Start_Date__c = System.today();
                                tenancyObject.Tenancy_Contract_Renewal_Steps__c = 'Renewal Started';
                                //Now Update the Tenancy Object...
                                update tenancyObject;
                                
                                integer slaHours = 0;
                                boolean slaFlag = false;
                                
                                for(SLA_Custom_Setting__c slaRecord : SLA_Custom_Setting__c.getAll().values())
                                {
                                    if(slaRecord.Application_Type__c == 'Tenancy Renewal' && slaRecord.Process_Type__c == 'License')
                                    {
                                        slaHours = integer.valueof(slaRecord.SLA_Hours__c);
                                        slaFlag  = true;
                                        break;
                                    }
                                                            
                                }
                                
                                if(slaFlag)
                                {
                                    // Assumes the BSC work hours are the default for the Org
                                    List<BusinessHours> businessHoursObjectList = new List<BusinessHours>([select id from businesshours where isDefault = true LIMIT 1]) ;
                                    
                                    if(businessHoursObjectList.size() > 0)
                                    {
                                    
                                        SLA__c slaObject = new SLA__c();
                                        slaObject.SLA_Hours__c = slaHours ;
                                        slaObject.Actual_Start_Date_Time__c = DateTime.Now();
                                        // BSC works 11.5 hours / day (8:00 AM - 7:30 PM, M-F). Our SLA is 2-days (23 business hours)
                                        System.debug('The Actual Start Time => '+ slaObject.Actual_Start_Date_Time__c );
                                        System.debug('The Expected End Date => '+ slaObject.Actual_Start_Date_Time__c.addhours(slaHours));
                                        System.debug('The Business Hour Date => ' + BusinessHours.add(businessHoursObjectList[0].id, slaObject.Actual_Start_Date_Time__c, slaHours * 60 * 60 * 1000L));
                                        System.debug('The Business Hour Date GMT => ' + BusinessHours.addGmt(businessHoursObjectList[0].id, slaObject.Actual_Start_Date_Time__c, slaHours * 60 * 60 * 1000L));
                                        slaObject.Expected_End_Date__c = BusinessHours.addGmt(businessHoursObjectList[0].id, slaObject.Actual_Start_Date_Time__c, slaHours * 60 * 60 * 1000L); 
                                                            
                                        //slaObject.Expected_End_Date__c = DateTime.Now().addhours(slaHours);
                                        slaObject.License__c = accountObject.Id ;
                                        slaObject.Tenancy_Contract__c = tenancyObject.Id;
                                        slaObject.Process_Type__c = 'License';
                                        slaObject.Application_Type__c = 'Tenancy Renewal';
                                        //Adding in the List...
                                        upsert slaObject;
                                    }
                                }
                                
                                //Refresh the page...
                                refreshPage = true;
                            
                                
                            }   
                        }
                        else
                        {
                            ApexPages.Message msg = new ApexPages.Message(ApexPages.Severity.INFO, 'This Account is Suspended, you need to approved it first !!!');
                            ApexPages.addMessage(msg);
                            return null;
                        }
                        
                        
                        
                        return null;
                    }
                    else
                    {
                        ApexPages.Message msg = new ApexPages.Message(ApexPages.Severity.INFO, 'Please review the Tenancy Contracts, One of the Location is no more associated to the tenancy Contract');
                        ApexPages.addMessage(msg);
                        return null;
                        
                    }   
                    
                    
                    
                    
                }
                else
                {               
                    ApexPages.Message msg = new ApexPages.Message(ApexPages.Severity.INFO, 'The License renewal cannot be performed at this step');
                    ApexPages.addMessage(msg);
                    return null;
                }
            }
            else
            {               
                ApexPages.Message msg = new ApexPages.Message(ApexPages.Severity.INFO, 'You are not authorize to initiate the renewal process');
                ApexPages.addMessage(msg);
                return null;
            }
            
            
            
            //Now Return the Values...
            return null;
        }
        catch(Exception ex)
        {
            System.debug(ex.getMessage());
            ApexPages.Message msg = new ApexPages.Message(ApexPages.Severity.INFO, 'The Error is => '+ex.getMessage() );
            ApexPages.addMessage(msg);
            return null;
        }
        
    }
    
    //For Renew Account Method...
    public PageReference renewAccountMethod()
    {
        try
        {
            if(accountObject.Login_User_Profile__c == 'SmartPaper BPM: 08 License - Front Office Payment User' || accountObject.Login_User_Profile__c == 'SmartPaper BPM: 01 Front Office User' || accountObject.Login_User_Profile__c == 'System Administrator')   
            {
                if(accountObject.License_Application_Step__c == 'Archived')
                {
                    
                    if(accountObject.Number_Of_Tenancy_Contract_Renwal__c == 0)
                    {
                        //Now Checking the All the Locations Related to the account...
                        List<Location__c> locationObjectList = new list<Location__c>([select Id,Current_Tenancy_Contract__c,name from Location__c where Current_Tenancy_Contract__c =: locationTennacyContractMap.keyset()]);
                        
                        //System.debug('The Total Number Of Locations are => '+ locationObjectList.size() + ' && the Total Number of Tenancy Contracts are => ' +locationTennacyContractMap.size());
                        
                        if(locationTennacyContractMap.size() > 0 )
                        {
                            //If the size is not equal to the tenancyObject then it is error...
                            if(locationObjectList.size() == locationTennacyContractMap.size())
                            {
                                
                                if(accountObject.Number_Of_Approved_Suspension_Record__c == 0)
                                {
                                    Boolean isContinueRenewal = true;
                                
                                    //Now Check the tenancy Contract Expired Comparison....
                                    for(Tenancy_Contract__c tenancyObject :tenancyContractList )
                                    {
                                        if((tenancyObject.Tenancy_Contract_Expiry_Date__c < System.Today() ) && ((tenancyObject.Account_Tenancy_Expriy_Difference__c) > integer.valueof(30)))
                                        {
                                            ApexPages.Message msg = new ApexPages.Message(ApexPages.Severity.INFO, 'Please perform the Tenancy Contract Renewal for Tenancy contract of "'+ tenancyObject.Name +'"');
                                            ApexPages.addMessage(msg);
                                            
                                            isContinueRenewal = false;
                                            
                                            break;
                                            
                                        }
                                    }
                                    
                                    if(isContinueRenewal)
                                    {
                                        //Updating some field...
                                        accountObject.License_Application_Type__c = 'Renewal';
                                        accountObject.License_Application_Step__c = 'Renewal Started';
                                        //RecordType recordType = [Select SobjectType, Name, IsActive, Id From RecordType where Name = 'Renewal' and IsActive = true and SobjectType = 'Account'];
                                        RecordType recordType = [Select SobjectType, DeveloperName,Name, IsActive, Id From RecordType where DeveloperName = 'Renewal_Front_Office' and IsActive = true and SobjectType = 'Account'];
                                        
                                        accountObject.RecordTypeId = recordType.id;
                                        //Comment as of 3rd September with new Change move to the Confirm Button...
                                        //accountObject.Renewal_Process_Start_Date__c = System.Today();
                                        accountObject.OwnerId = accountObject.Login_User_Id__c;
                                        accountObject.Record_Approver_Id__c = accountObject.Login_User_Id__c;
                                        //Now Update the Account...
                                        update accountObject;
                                        
                                        
                                        integer slaHours = 0;
                                        boolean slaFlag = false;
                                        
                                        for(SLA_Custom_Setting__c slaRecord : SLA_Custom_Setting__c.getAll().values())
                                        {
                                            if(slaRecord.Application_Type__c == 'Renewal' && slaRecord.Process_Type__c == 'License')
                                            {
                                                slaHours = integer.valueof(slaRecord.SLA_Hours__c);
                                                slaFlag  = true;
                                                break;
                                            }
                                                                    
                                        }
                                        
                                        if(slaFlag)
                                        {
                                            // Assumes the BSC work hours are the default for the Org
                                            List<BusinessHours> businessHoursObjectList = new List<BusinessHours>([select id from businesshours where isDefault = true LIMIT 1]) ;
                                            
                                            if(businessHoursObjectList.size() > 0)
                                            {
                                                SLA__c slaObject = new SLA__c();
                                                slaObject.SLA_Hours__c = slaHours ;
                                                slaObject.Actual_Start_Date_Time__c = DateTime.Now();
                                                // BSC works 11.5 hours / day (8:00 AM - 7:30 PM, M-F). Our SLA is 2-days (23 business hours)
                                                System.debug('The Actual Start Time => '+ slaObject.Actual_Start_Date_Time__c );
                                                System.debug('The Expected End Date => '+ slaObject.Actual_Start_Date_Time__c.addhours(slaHours));
                                                System.debug('The Business Hour Date => ' + BusinessHours.add(businessHoursObjectList[0].id, slaObject.Actual_Start_Date_Time__c, slaHours * 60 * 60 * 1000L));
                                                System.debug('The Business Hour Date GMT => ' + BusinessHours.addGmt(businessHoursObjectList[0].id, slaObject.Actual_Start_Date_Time__c, slaHours * 60 * 60 * 1000L));
                                                slaObject.Expected_End_Date__c = BusinessHours.addGmt(businessHoursObjectList[0].id, slaObject.Actual_Start_Date_Time__c, slaHours * 60 * 60 * 1000L); 
                                                //slaObject.Expected_End_Date__c = DateTime.Now().addhours(slaHours);
                                                slaObject.License__c = accountObject.Id ;
                                                slaObject.Process_Type__c = 'License';
                                                slaObject.Application_Type__c = 'Renewal';
                                                //Adding in the List...
                                                upsert slaObject;
                                           }
                                        }
                                      
                                        //Refresh the page...
                                        refreshPage = true;
                                    
                                        
                                    }   
                                }
                                else
                                {
                                    ApexPages.Message msg = new ApexPages.Message(ApexPages.Severity.INFO, 'This Account is Suspended, you need to approved it first !!!');
                                    ApexPages.addMessage(msg);
                                    return null;
                                }
                                
                                
                                
                                return null;
                            }
                            else
                            {
                                ApexPages.Message msg = new ApexPages.Message(ApexPages.Severity.INFO, 'Please review the Tenancy Contracts, One of the Location is no more associated to the tenancy Contract');
                                ApexPages.addMessage(msg);
                                return null;
                                
                            } 
                                
                        }
                        else
                        {
                            ApexPages.Message msg = new ApexPages.Message(ApexPages.Severity.INFO, 'There is no Active Tenancy Contract associated with this Account...');
                            ApexPages.addMessage(msg);
                            return null;
                        }
                          
                    }
                    else
                    {               
                        ApexPages.Message msg = new ApexPages.Message(ApexPages.Severity.INFO, 'One of the Tenancy Contract still in the process of Renewal, Please first renewed that Tenancy Contract');
                        ApexPages.addMessage(msg);
                        return null;
                    }
                    
                    
                    
                    
                }
                else
                {               
                    ApexPages.Message msg = new ApexPages.Message(ApexPages.Severity.INFO, 'The License renewal cannot be performed at this step');
                    ApexPages.addMessage(msg);
                    return null;
                }
            }
            else
            {               
                ApexPages.Message msg = new ApexPages.Message(ApexPages.Severity.INFO, 'You are not authorize to initiate the renewal process');
                ApexPages.addMessage(msg);
                return null;
            }
        }
        catch(Exception ex)
        {
            System.debug(ex.getMessage());
            ApexPages.Message msg = new ApexPages.Message(ApexPages.Severity.INFO, 'The Error is => '+ex.getMessage() );
            ApexPages.addMessage(msg);
            return null;
            
        }
            
    }
    

}